package com.admin.system.modules.mnt.rest;

import com.admin.common.exception.BadRequestException;
import com.admin.common.utils.FileUtil;
import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.logging.annotation.Log;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.system.modules.mnt.dto.DatabaseQueryDTO;
import com.admin.system.modules.mnt.entity.Database;
import com.admin.system.modules.mnt.service.DatabaseService;
import com.admin.system.modules.mnt.util.SqlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author sq-lan
 */
@Api(tags = "运维：数据库管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/database")
public class DatabaseController {

    private final String fileSavePath = FileUtil.getTmpDirPath() + "/";
    private final DatabaseService databaseService;

    @ApiOperation(value = "查询")
    @GetMapping
    @PreAuthorize("@ss.check('database:list')")
    public ResponseEntity<PageResult<Database>> paging(DatabaseQueryDTO dto) {
        return new ResponseEntity<>(databaseService.paging(dto), HttpStatus.OK);
    }

    @Log(module = "数据库管理", operateType = OperateTypeEnum.ADD)
    @ApiOperation(value = "新增")
    @PostMapping
    @PreAuthorize("@ss.check('database:add')")
    public ResponseEntity<Object> add(@Validated @RequestBody Database entity) {
        databaseService.add(entity);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log(module = "数据库管理", operateType = OperateTypeEnum.MODIFY)
    @ApiOperation(value = "修改")
    @PutMapping
    @PreAuthorize("@ss.check('database:edit')")
    public ResponseEntity<Object> modify(@Validated @RequestBody Database entity) {
        databaseService.modify(entity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log(module = "数据库管理", operateType = OperateTypeEnum.REMOVE)
    @ApiOperation(value = "删除")
    @DeleteMapping
    @PreAuthorize("@ss.check('database:del')")
    public ResponseEntity<Object> remove(@RequestBody Set<String> ids) {
        databaseService.remove(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log(module = "数据库管理-测试链接")
    @ApiOperation(value = "测试数据库链接")
    @PostMapping("/testConnect")
    @PreAuthorize("@ss.check('database:testConnect')")
    public ResponseEntity<Object> testConnect(@Validated @RequestBody Database entity) {
        return new ResponseEntity<>(databaseService.testConnection(entity), HttpStatus.CREATED);
    }

    @Log(module = "数据库管理-执行SQL脚本")
    @ApiOperation(value = "执行SQL脚本")
    @PostMapping(value = "/upload")
    @PreAuthorize("@ss.check('database:add')")
    public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");
        Database database = databaseService.getById(id);
        String fileName;
        if (database != null) {
            fileName = file.getOriginalFilename();
            File executeFile = new File(fileSavePath + fileName);
            FileUtil.del(executeFile);
            file.transferTo(executeFile);
            String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } else {
            throw new BadRequestException("Database not exist");
        }
    }


    @ApiOperation("导出数据库数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check('database:list')")
    public void export(HttpServletResponse response, DatabaseQueryDTO dto) throws IOException {
        List<Database> databases = databaseService.list(dto);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Database database : databases) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("数据库名称", database.getName());
            map.put("数据库连接地址", database.getJdbcUrl());
            map.put("用户名", database.getUserName());
            map.put("创建日期", database.getCreateTime());
            list.add(map);
        }
        MultipartFileUtil.downloadExcel(list, response);
    }
}
